import React, { Component } from 'react'
import { Text, View, Animated, StatusBar, StyleSheet, Image, TouchableOpacity, Dimensions, TouchableWithoutFeedback } from 'react-native'
import Video from 'react-native-video'
import Slider from '@react-native-community/slider'
import { linear } from 'react-native/Libraries/Animated/Easing'
import { BlurView } from "@react-native-community/blur"
import { Toast, Provider } from '@ant-design/react-native';
import { formateSeconds } from '../utils/timeUtil'
import axios from 'axios'
import qs from 'qs'

const dataUrl = "http://120.53.227.202:8080/music/api/music/"
const musicUrl = "http://120.53.227.202/resources/rn_music/mp3/"


const start = require('../sources/handler/start.png')
const stop = require('../sources/handler/stop.png')
const close = require('../sources/handler/close.png')
const share = require('../sources/handler/share.png')
const musicbg = require('../sources/handler/musicbg.png')
const zhen = require('../sources/handler/zhen.png')
const lastone = require('../sources/handler/lastone.png')
const nextone = require('../sources/handler/nextone.png')
const musiclist = require('../sources/handler/musiclist.png')
const repeat = require('../sources/handler/repeat.png')
const whitedot = require('../sources/handler/whitedot.png')

const volume0 = require('../sources/handler/volume0.png')
const volume1 = require('../sources/handler/volume1.png')
const volumedot = require('../sources/handler/volumedot.png')

const like = require('../sources/Music/like.png')
const nolike = require('../sources/Music/nolike.png')


const Phonewidth = Dimensions.get('screen').width
const PhoneHeight = Dimensions.get('screen').height



export default class Music extends Component {
    rv = 0//动画当前值
    state = {
        musics: [], mIndex: 0, paused: true, duration: 0, currentTime: 0,
        rotate: new Animated.Value(0),
        zhen: new Animated.Value(0),
        lyric_state: true,
        volume: 1,
    }
    componentDidMount() {
        this.state.rotate.addListener(({ value }) => this.rv = value) //添加动画值的变化监听器
        //获取整个⾳乐列表
        // fetch(dataUrl).then(resp => resp.json())
        //     .then(data => this.setState({ musics:data.obj }))

        if (this.props.route.params != undefined) {
            let music = new Array()
            music.push(this.props.route.params)
            this.setState({ musics: music })
        } else {
            fetch(dataUrl).then(resp => resp.json())
                .then(data => this.setState({ musics: data.obj, mIndex: Math.round(Math.random() * 10) }))
        }




        // console.log(PhoneHeight, Phonewidth)
    }
    //播放暂停
    _palyOrPause = () => {
        //播放针头的播放暂停动画
        let zhenStart = Animated.timing(this.state.zhen, { toValue: 25, duration: 500, useNativeDriver: true, easing: linear })
        let zhenStop = Animated.timing(this.state.zhen, { toValue: 0, duration: 500, useNativeDriver: true, easing: linear })
        //设计动画对象
        let an = Animated.loop(Animated
            .timing(this.state.rotate,
                { useNativeDriver: true, duration: 10000, toValue: this.rv + 360, easing: linear }))
        this.state.paused ? an.start() : an.stop()//控制光盘旋转动画
        this.state.paused ? zhenStart.start() : zhenStop.start()
        this.setState(state => ({ paused: !state.paused }))
    }
    //歌曲加载后，更新duration状态
    _load = ({ duration }) => this.setState({ duration })
    //进度显示控制
    _progress = ({ currentTime }) => this.setState({ currentTime })
    //快速定位
    _seek = val => this.player.seek(val)
    //换曲/下一曲
    _end = () => {
        let songsNum = this.state.musics.length
        this.setState(state => ({ mIndex: ++state.mIndex % songsNum }))
    }
    //上一曲
    _lastmusic = () => {
        if (this.state.mIndex != 0) {
            this.setState(state => ({ mIndex: --state.mIndex }))
        }

    }
    //切换中间显示内容
    _changecontent = () => {
        this.setState(state => ({ lyric_state: !state.lyric_state }))
    }

    //调节音量
    _volume = val => { this.setState(() => ({ volume: val })) }



    _close = () => {
        this.props.navigation.goBack()
    }

    _like(islike, inx) {
        if (islike == 0) {
            let musics = this.state.musics
            Toast.success('已添加到喜欢', 1)
            musics[inx].islike = 1
            this.setState({ musics })
            axios.put(dataUrl, qs.stringify({
                id: musics[inx].id,
                name: musics[inx].name,
                islike: 1,
                singer: musics[inx].toString()
            })).then(resp => {
                if (!resp.data.result) {
                    Toast.fail('添加失败')
                    musics[inx].islike = 0
                    this.setState({ musics })
                }
            })
        } else {
            let musics = this.state.musics
            Toast.success('已取消喜欢', 1)
            musics[inx].islike = 0
            this.setState({ musics })
            axios.put(dataUrl, qs.stringify({
                id: musics[inx].id,
                name: musics[inx].name,
                islike: 0,
                singer: musics[inx].toString()
            })).then(resp => {
                if (!resp.data.result) {
                    Toast.fail('取消失败')
                    musics[inx].islike = 0
                    this.setState({ musics })
                }
            })
        }
    }

    render() {
        let { musics: mus, mIndex: inx } = this.state
        //应⽤于光盘对象的动画CSS
        let style = {
            transform:
                [{
                    rotate: this.state.rotate
                        .interpolate({ inputRange: [0, 360], outputRange: ['0deg', '360deg'] })
                }]
        }

        let volumeSlider = <Slider
            onValueChange={this._volume}
            value={this.state.volume}
            maximumValue={1}
            thumbTintColor='white'
            minimumTrackTintColor='#DCDFE6'
            maximumTrackTintColor='#EBEEF5'
            inverted={this.state.lyric_state}
            thumbImage={whitedot}
        />



        return (
            <Provider>
                <View style={{ flex: 1, backgroundColor: '#606266' }}>
                    {/* 设置顶部手机的状态栏 */}
                    {/* <StatusBar translucent={true} backgroundColor="transparent" /> */}
                    {/* 渐变色组件，暂时不用 */}
                    {/* <LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}></LinearGradient> */}

                    <Image source={{ uri: musicUrl + mus[inx]?.name + ".png" }} style={{ position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, height: '300%', width: '300%' }} />
                    <BlurView
                        style={{ position: "absolute", top: 0, left: 0, bottom: 0, right: 0 }}
                        blurType='light'
                        blurAmount={100}
                    />
                    <Video ref={ref => this.player = ref}
                        volume={this.state.volume}
                        onEnd={this._end}
                        paused={this.state.paused} onProgress={this._progress}
                        onLoad={this._load}
                        source={{ uri: musicUrl + mus[inx]?.name + ".mp3" }} />

                    {/* 顶部导航栏位置 */}
                    <View style={{ display: 'flex', width: '100%', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', height: 50, marginTop: 35, paddingLeft: 20, paddingRight: 20 }}>
                        <TouchableOpacity onPress={() => this._close()}>
                            <View>
                                <Image source={close} style={{ width: 25, height: 25 }} />
                            </View>
                        </TouchableOpacity>
                        <View style={{ display: 'flex', flexDirection: 'column' }}>
                            <Text style={{ fontSize: 17, textAlign: 'center', color: '#FFFFFF' }}> {mus[inx]?.name}</Text>
                            <Text style={{ fontSize: 10, textAlign: 'center', color: '#E2DFE0' }}>{mus[inx]?.singer.join(',')}</Text>

                        </View>
                        <View><Image source={share} style={{ width: 25, height: 25 }} /></View>

                    </View>
                    {/* onPress={this._changecontent} */}
                    <TouchableWithoutFeedback >
                        <View style={this.state.lyric_state ? styles.music : styles.hidden}>
                            <View style={{ flexDirection: 'column-reverse' }}>
                                <View style={{ flex: 1, justifyContent: 'flex-end' }}>
                                    <TouchableOpacity onPress={() => this._like(mus[inx]?.islike, inx)} style={{ width: 25, height: 25, marginBottom: 20 }}>
                                        <Image source={mus[inx]?.islike == 0 ? nolike : like} style={{ width: 25, height: 25 }} />
                                    </TouchableOpacity>
                                </View>
                                <View style={{ marginTop: 80 }}>
                                    <Animated.Image
                                        style={[style, { width: Phonewidth * 0.73, height: Phonewidth * 0.73, borderRadius: 150, alignSelf: 'center', resizeMode: 'stretch' }]}
                                        source={musicbg} />
                                    <Animated.Image
                                        style={[style, { width: Phonewidth * 0.5, height: Phonewidth * 0.5, borderRadius: 150, alignSelf: 'center', resizeMode: 'stretch', position: 'absolute', marginTop: 45 }]}
                                        source={{ uri: musicUrl + mus[inx]?.name + ".png" }} />

                                </View>

                                <View style={{ marginLeft: 10, height: PhoneHeight * 0.12, marginTop: -80 }}>
                                    <Animated.Image source={zhen} resizeMethod='scale' style={{ width: Phonewidth * 0.68, height: Phonewidth * 0.68 * 0.71, transform: [{ rotate: this.state.zhen.interpolate({ inputRange: [0, 360], outputRange: ["0deg", "360deg"] }) }] }} />
                                </View>



                            </View>
                        </View>
                    </TouchableWithoutFeedback>



                    <View style={this.state.lyric_state ? styles.hidden : styles.lyric}>
                        <View style={{ margin: 5, display: 'flex', flexDirection: 'row', width: '100%', paddingLeft: 15, paddingRight: 15 }}>
                            <Image source={this.state.volume == 0 ? volume0 : volume1} style={{ width: 15, height: 15 }} />
                            <View style={{ flex: 1, paddingRight: 15 }}>
                                {this.state.lyric_state ? null : volumeSlider}
                            </View>

                        </View>

                        <TouchableWithoutFeedback onPress={this._changecontent}>
                            <View style={{ flex: 1, justifyContent: 'center', width: "100%" }}>
                                <Text style={{ textAlign: 'center', fontSize: 17, color: '#EBEEF5', fontWeight: 'bold' }}>暂无歌词</Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>





                    <View style={{ paddingLeft: 20, paddingRight: 20, height: 120 }}>
                        <View style={{ display: 'flex', width: '100%', flexDirection: 'row', alignItems: 'center' }}>
                            <Text style={{ color: '#EBEEF5', fontSize: 10 }}>{formateSeconds(this.state.currentTime)}</Text>
                            <View style={{ flex: 1, marginTop: 5, marginBottom: 5 }}>
                                <Slider
                                    onSlidingComplete={this._seek}
                                    value={this.state.currentTime}
                                    maximumValue={this.state.duration}
                                    thumbTintColor='white'
                                    minimumTrackTintColor='#DCDFE6'
                                    maximumTrackTintColor='#EBEEF5'
                                    thumbImage={whitedot}
                                />
                            </View>
                            <Text style={{ color: '#EBEEF5', fontSize: 10 }}>{formateSeconds(this.state.duration)}</Text>
                        </View>

                        {/* 播放暂停控制器 */}
                        {/* <Button title={this.state.paused ? "播放" : "暂停"}
                    onPress={this._palyOrPause} /> */}
                        <View style={{ marginTop: 10, marginBottom: 10, marginLeft: 20, marginRight: 20, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                            <TouchableOpacity onPress={this._palyOrPause} style={{ width: 25, height: 25 }}>
                                <Image source={repeat} style={{ width: 25, height: 25 }} />
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this._lastmusic} style={{ width: 25, height: 25 }}>
                                <Image source={lastone} style={{ width: 25, height: 25 }} />
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this._palyOrPause} style={{ width: 60, height: 60 }}>
                                <Image source={this.state.paused ? start : stop} style={{ width: 60, height: 60 }} />
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this._end} style={{ width: 25, height: 25 }}>
                                <Image source={nextone} style={{ width: 25, height: 25 }} />
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this._palyOrPause} style={{ width: 25, height: 25 }}>
                                <Image source={musiclist} style={{ width: 25, height: 25 }} />
                            </TouchableOpacity>
                        </View>

                    </View>


                </View>
            </Provider>
        )
    }
}

const styles = StyleSheet.create({
    linearGradient: {
        flex: 1,
    },
    hidden: {
        display: 'none'
    },
    lyric: {
        flex: 1
    },
    music: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    vmslider: {
        marginTop: -1000
    }
});